package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.entity.UserInfo;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Result send(String phone, HttpSession session) {
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误");
        }
        String redisCodeKey = LOGIN_CODE_KEY + phone;
        String redisCode = (String) redisTemplate.opsForValue().get(redisCodeKey);
        //验证码两分钟有效
        if (redisCode != null) {
            return Result.fail("验证码已发送，请稍后再试");
        }
        //生成验证码
        String code = RandomUtil.randomNumbers(6);
        redisTemplate.opsForValue().set(redisCodeKey, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        log.info("验证码为：{}", code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String userPhone = loginForm.getPhone();
        //检验手机号
        if (RegexUtils.isPhoneInvalid(userPhone)) {
            return Result.fail("手机号格式错误");
        }
        String redisCodeKey = LOGIN_CODE_KEY + userPhone;
        String cacheCode = (String) redisTemplate.opsForValue().get(redisCodeKey);
        String userCode = loginForm.getCode();
        if (StrUtil.isBlank(userCode) || !Objects.equals(cacheCode, userCode)) {
            return Result.fail("验证码错误");
        }
        //判断有没有注册过
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone, userPhone);
        User user = getOne(lqw);
        if (Objects.isNull(user)) {
            //注册
            user = createUserWithPhone(userPhone);
        }
        String token = UUID.randomUUID().toString();
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        String userInfoKey = LOGIN_USER_KEY + token;
        Map<String, Object> map = BeanUtil.beanToMap(userDTO);
        //hash的形式存入redis
        redisTemplate.opsForHash().putAll(userInfoKey, map);
        //设置有效期
        redisTemplate.expire(userInfoKey, CACHE_USER_TTL, TimeUnit.MINUTES);
        return Result.ok(token);
    }

    @Override
    public Result me() {
        UserDTO userDTO = UserHolder.getUser();
        System.out.println(userDTO);
        return Result.ok(userDTO);
    }

    private User createUserWithPhone(String userPhone) {
        User user = new User();
        user.setPhone(userPhone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        save(user);
        return user;
    }
}
